const USERNAME = localStorage.getItem('username');

init();
function init() {
    fetch(`http://localhost/friends/getOwnFriends?username=${USERNAME}`, {
        method: 'GET', // 指定请求方法为 GET
        headers: {
            'Content-Type': 'application/json',// 指定请求头
            'Authorization': localStorage.getItem("token")
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.flag) {
                const userListDiv = document.getElementById('user-list');
                data.data.forEach(item => {
                    var user;
                    if (item.note != null) {
                        user = item.note;
                    }else{
                        user = item.friend_name;
                    }
                    // 创建用户条目的 HTML
                    const userItemHtml = `
                            <div onclick="showUserInfo('${user}','${item.friend_name}',this)" class="user-item">
                                <img class="user-avatar" src="./favicon.ico">
                                <div class="user-name">${user}</div>
                            </div>
                        `;
                    // 将用户条目的 HTML 添加到 userListDiv 中
                    userListDiv.innerHTML += userItemHtml;

                });

            }else {
                alert('获取好友列表失败，' + data.message)
                console.error('获取好友列表失败:', data.message);
            }
        })
        .catch(error => {
            console.error('请求出现问题:', error);
            // localStorage.clear();
            // alert('您尚未登录，请先登录！');
            // window.location.href = 'login.html'
        });
}






function showUserInfo(note,name,element) {
    // 先把好友请求列表隐藏掉
    document.querySelector(".friend-request-list").style.display = 'none';

    const items = document.querySelectorAll('.user-item');
    items.forEach(item => item.classList.remove('selected'));
    element.classList.add('selected');
    document.querySelector('.user-info').style.display = 'flex'
    document.getElementById("friend-name").innerText = note;
    document.querySelector(".username").innerText = name;
    if (note != name) {
        document.querySelector('.note-div input').value = note;
    } else {
        document.querySelector('.note-div input').value = '';

    }


}
// 点击时添加样式
function changeTheInput(input) {
    input.classList.add('input-with-css');
    input.placeholder = '';
}


// 失去焦点时恢复原状
function restoreTheInput(input) {
    input.classList.remove('input-with-css');
    restoreNote(input)
}
function restoreNote(element) {
    var note = element.value;

    const noteData = {
        username: USERNAME,
        friendName: document.querySelector('.selected .user-name').innerText,
        note: note
    }

    if (note != null && note != '') {
        document.getElementById('friend-name').innerText = note;
        document.querySelector('.selected .user-name').innerText = note;
        element.placeholder = note;
        // element.placeholder.style.color = 'black';
    } else {
        document.querySelector('.selected .user-name').innerText =  document.querySelector('.username').innerText;
        document.getElementById('friend-name').innerText = document.querySelector('.username').innerText;
        element.placeholder = '点击添加备注';
        element.placeholder.style.color = '#bdbdbd';
    }

    // 发送请求 插入备注
    fetch('http://localhost/friends/updateNote', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': localStorage.getItem("token")
        },
        body: JSON.stringify(noteData)
    }).then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json(); // 解析响应的JSON数据
    })
        .then(data => {
            if (data.flag) {
                console.log('添加备注成功');
            }else {
                console.log('添加备注失败');
            }
        })
        .catch(error => {
            // 处理请求过程中的错误
            console.error('请求出现问题:', error);

        });
}
function handleKeyDown(event, element) {
    if(event.keyCode === 13){
        event.preventDefault();
        if (element.value.trim() !== '') {
            restoreNote(element);
        }
    }
}
function chatWho(element) {
    var value = element.querySelector('#friend-name').innerText;
    var real = element.querySelector(".username").innerText;
    window.location.href = `main.html?point=${value}&real=${real}`
}

function resetInput(element) {


    element.classList.add('reset');
    document.querySelector("#x").style.display = 'block';
    element.placeholder = '';

    // clearList();
    var searchDiv = document.querySelector(".search-div");
    var sibling = searchDiv.nextSibling;
    // 移除searchDiv之后的所有兄弟元素
    while (sibling) {

        var nextSibling = sibling.nextSibling;
        if (sibling.classList && (sibling.classList.contains("search-friend") || sibling.classList.contains("search-box"))) {
            var nextSibling = sibling.nextSibling;
            sibling = nextSibling;
            continue;
        }
        sibling.parentNode.removeChild(sibling);
        sibling = nextSibling;
    }

}


// function clearList(element) {
//
//
// }
function unsetInput(element) {
    element.querySelector("input").classList.remove('reset');
    element.querySelector("input").placeholder = '搜索';
    //清除
    var searchDiv = document.querySelector(".search-div");
    var sibling = searchDiv.nextSibling;
    // 移除searchDiv之后的所有兄弟元素
    while (sibling) {
        var nextSibling = sibling.nextSibling;
        if (sibling.classList && (sibling.classList.contains("search-friend") || sibling.classList.contains("search-box"))) {
            var nextSibling = sibling.nextSibling;
            sibling = nextSibling;
            continue;
        }
        sibling.parentNode.removeChild(sibling);
        sibling = nextSibling;
    }

    init();
    document.querySelector("#x").style.display = 'none';

}
function searchFriend(element) {
    var searchDiv = document.querySelector(".search-div");
    var sibling = searchDiv.nextSibling;

    // 移除searchDiv之后的所有兄弟元素
    while (sibling) {
        if (sibling.classList && (sibling.classList.contains("search-friend") || sibling.classList.contains("search-box"))) {
            var nextSibling = sibling.nextSibling;
            sibling = nextSibling;
            continue;
        }
        var nextSibling = sibling.nextSibling;
        sibling.parentNode.removeChild(sibling);
        sibling = nextSibling;
    }
    var key = element.value;
    fetch(`http://localhost/friends/searchFriend?username=${USERNAME}&key=${key}`, {
        method: 'GET', // 指定请求方法为 GET
        headers: {
            'Content-Type': 'application/json',// 指定请求头
            'Authorization': localStorage.getItem("token")
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.flag) {
                const userListDiv = document.getElementById('user-list');
                data.data.forEach(item => {
                    var user;
                    if (item.note != null) {
                        user = item.note;
                    }else{
                        user = item.friend_name;
                    }
                    // 创建用户条目的 HTML
                    // const userItemHtml = `
                    //         <div onclick="showUserInfo('${user}','${item.friend_name}',this)" class="user-item">
                    //             <img class="user-avatar" src="./favicon.ico">
                    //             <div class="user-name">${user}</div>
                    //         </div>
                    //     `;
                    // // 将用户条目的 HTML 添加到 userListDiv 中
                    // if (item.friend_name != USERNAME) {
                    //     userListDiv.innerHTML += userItemHtml;
                    // }
                    var userItem = document.createElement('div');
                    userItem.classList.add('user-item');
                    userItem.setAttribute('onclick', `showUserInfo('${user}','${item.friend_name}',this)`);

                    var userAvatar = document.createElement('img');
                    userAvatar.classList.add('user-avatar');
                    userAvatar.setAttribute('src', './favicon.ico');
                    userItem.appendChild(userAvatar);

                    var userName = document.createElement('div');
                    userName.classList.add('user-name');
                    userName.textContent = user;
                    userItem.appendChild(userName);

                    // 将新的用户条目元素添加到 userListDiv 中
                    if (item.friend_name != USERNAME) {
                        userListDiv.appendChild(userItem);
                    }
                });

            }else {
                console.error('根据关键字搜索朋友失败:', data.message);
            }
        })
        .catch(error => {
            console.error('根据关键字搜索朋友出现问题:', error);
        });
}
function hiddenPlaceholder(element) {
    // 清空 placeholder
    element.placeholder = "";
}

// 添加blur事件监听器
function showPlaceholder(element) {
    // 恢复 placeholder
    element.placeholder = "用户名";
}

function change1(element) {
    if (element.value == null || element.value == '') {
        document.querySelector(".search-box").style.display = 'none';
    } else {
        document.querySelector(".search-box").style.display = 'flex';
    }
    document.getElementById("change1").innerText = element.value
}
function addFriend(element) {
    element.querySelector("input").value = '';
    var searchDiv = document.querySelector(".search-div");
    var sibling = searchDiv.nextSibling;
    // 移除searchDiv之后的所有兄弟元素
    while (sibling) {
        var nextSibling = sibling.nextSibling;
        if (sibling.classList && (sibling.classList.contains("search-friend") || sibling.classList.contains("search-box"))) {
            var nextSibling = sibling.nextSibling;
            sibling = nextSibling;
            continue;
        }
        sibling.parentNode.removeChild(sibling);
        sibling = nextSibling;
    }

    element.style.display = 'none';
    document.querySelector('.search-friend').style.display = 'flex';

}
function recover(element) {
    unsetInput(document.querySelector('.search-div'));
    element.style.display = 'none';
    document.querySelector('.search-div').style.display = 'flex';
    document.querySelector(".search-box").style.display = 'none';
    element.querySelector("input").value = '';
}

function doSearch() {
    var value = document.querySelector(".search-friend input").value;
    // 去发请求查看到底有没有这个人
    // 直接发送增加
    fetch(`http://localhost/friends/verifyFriend?username=${value}`, {
        method: 'GET', // 指定请求方法为 GET verify
        headers: {
            'Content-Type': 'application/json',// 指定请求头
            'Authorization': localStorage.getItem("token")
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.flag) {
                //要发送的信息
                var message = data.data
                document.getElementById("messageBox").innerText = message;
                showMessageBox();
            }else {
            }
        })
        .catch(error => {
            console.error('请求出现问题:', error);
        });


}

function showMessageBox() {
    var messageBox = document.getElementById("messageBox");
    messageBox.style.display = "block";
    setTimeout(function(){
        messageBox.style.display = "none";
    }, 2000);
}

//显示聊天列表 前端把user-info隐藏掉 展示好友请求列表 然后在showUserInfo也进行处理隐藏本元素 展示用户信息

function showFriendRequest(element) {
    const items = document.querySelectorAll('.user-item');
    items.forEach(item => item.classList.remove('selected'));
    element.classList.add('selected');
    document.querySelector('.user-info').style.display = 'none';
    document.querySelector('.friend-request-list').style.display = 'flex';

    fetch(`http://localhost/friends/selectRequest`, {
        method: 'GET', // 指定请求方法为 GET
        headers: {
            'Content-Type': 'application/json',// 指定请求头
            'Authorization': localStorage.getItem("token")
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.flag) {

                const requestList = document.querySelector('.friend-request-list');
                data.data.forEach(item => {
                    // 创建用户条目的 HTML
                    const userItemHtml1 = `
                            <div class="friend-request-item">
                                <img src="favicon.ico">
                                <div>${item.sender_username}</div>
                                <div class="unaccepted">已添加</div>
                            </div>
                        `;
                    const userItemHtml2 = `
                            <div class="friend-request-item">
                                <img src="favicon.ico">
                                <div>${item.sender_username}</div>
                                <div onclick="acceptRequest(this,'${item.sender_username}')" class="accepted">接受</div>
                            </div>
                        `;
                    // 先清除一下类表，分情况把HTML添加到requestList中
                    var div = document.querySelector(".request-head");
                    var sibling = div.nextSibling;

                    // 移除searchDiv之后的所有兄弟元素
                    while (sibling) {
                        if (sibling.classList && (sibling.classList.contains("search-friend") || sibling.classList.contains("search-box"))) {
                            var nextSibling = sibling.nextSibling;
                            sibling = nextSibling;
                            continue;
                        }
                        var nextSibling = sibling.nextSibling;
                        sibling.parentNode.removeChild(sibling);
                        sibling = nextSibling;
                    }
                    if (item.status == "已添加") {
                        requestList.innerHTML += userItemHtml1;
                    } else {
                        requestList.innerHTML += userItemHtml2;
                    }


                });
            }else {
                console.error('获取好友请求列表失败:', data.message);
            }
        })
        .catch(error => {
            console.error('请求出现问题:', error);
        });
}



function acceptRequest(element,sender_username) {
    // 发送PATCH请求 把请求值改成已添加
    fetch(`http://localhost/friends/agreeRequest/${sender_username}`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': localStorage.getItem("token")
        }
    }).then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json(); // 解析响应的JSON数据
    })
        .then(data => {
            if (data.flag) {
                document.getElementById("messageBox").innerText = '好友同意成功';
                showMessageBox();

                // 把此条消息改成已添加,css类也改变
                element.innerText = '已添加'
                element.classList.remove("accepted")
                element.classList.add("unaccepted")

                // 然后就加好友
                fetch('http://localhost/friends/addFriend', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': localStorage.getItem("token")
                    },
                    body: JSON.stringify({ sender_username: sender_username })
                }).then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json(); // 解析响应的JSON数据
                }).then(data => {
                    if (data.flag) {
                        document.getElementById("messageBox").innerText = '添加好友成功';
                        showMessageBox();
                    }else {
                        document.getElementById("messageBox").innerText = '添加好友成功';
                        showMessageBox();
                    }
                }).catch(error => {
                    console.error('请求出现问题:', error);
                });




            } else {
                console.log('好友同意失败');
            }
        })
        .catch(error => {
            console.error('请求出现问题:', error);

        });
    // 然后POST请求 加好友
}
